<!DOCTYPE html>
<html lang="ru">
    <head>
        <meta charset="utf-8"/>
        <meta name="viewport" content="width=device-width, initial-scale=1.0">

        <link 
            href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css" 
            rel="stylesheet">
        <link rel="stylesheet" href="css/appctl.css" media="screen">

        <!---->
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
        <script src="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/js/bootstrap.min.js"></script>

        <script>
            var dojoConfig = {
                async: true
            };
        </script>
        <!--script src="js/slibs/dojo/dojo.js"></script-->
        <script src="//ajax.googleapis.com/ajax/libs/dojo/1.9.1/dojo/dojo.js"></script>

        <script type="text/javascript">
            require([
                "dojo/_base/lang",
                "dojo/_base/fx",
                "dojo/request/notify",
                "dojo/store/JsonRest",
                "dojo/store/Memory",
                "dojo/store/Cache",
                "dojo/query",
                "dojo/dom-construct",
                "dojo/fx",
                "dojo/on",
                "dojo/dom-form",
                "dojo/domReady!"
            ], function(lang,
                    baseFx,
                    notify,
                    JsonRest,
                    Memory,
                    Cache,
                    query,
                    domConstruct,
                    fx,
                    on,
                    domForm) {

                fx.wipeOut({node: 'errorAlert'}).play(); //dipslay:none для прозрачного диалога

                function Model() {
                    var jsonRest = new JsonRest({target: "rst/user/"});
                    var cacheStore = new Memory({});
                    var userStore = new Cache(jsonRest, cacheStore);

                    var callbacks = {};

                    function userJsonRewrite(srvUser) {
                        return srvUser.user ? srvUser.user : srvUser;
                    }

                    function fireCallbacks(callbacksArray, args) {
                        if (callbacksArray && callbacksArray.length) {
                            for (var i = 0; i < callbacksArray.length; i++) {
                                callbacksArray[i](args);
                            }
                        }
                    }

                    return {
                        registerCallback: function(event, callback) {
                            console.log(callbacks[event]);
                            callbacks[event] = callbacks[event] ? callbacks[event] : [];
                            callbacks[event].push(callback);
                        },
                        get: function(id) {
                            userStore.get(id).then(function(srvUser) {
                                console.log("get in Controller(" + id + ")=" + srvUser);
                                srvUser = userJsonRewrite(
                                        srvUser
                                        );
                                var callbacksArray = callbacks['get'];
                                fireCallbacks(callbacksArray, srvUser);
                            });

                        },
                        query: function(queryObj) {
                            for (var p in queryObj) {
                                if (!queryObj[p]) {//delete empty query params
                                    delete queryObj[p];
                                }
                            }
                            fireCallbacks(callbacks['beforeQuery'], queryObj);
                            return userStore.query(queryObj)
                                    .then(function(srvUsers) {
                                fireCallbacks(callbacks['query'], userJsonRewrite(srvUsers));
                            });


                        }
                    };
                }

                function View() {

                    function makeRow(user, node) {
                        var clz = user.lastName ? '' : 'warning';
                        clz = (user.enabled == 'y') ? clz : 'error';
                        // clz=clz.trim();
                        domConstruct.create("tr", {class: clz,
                            innerHTML: makeCell(user.idUser) +
                                    makeCell(user.login) +
                                    makeCell(user.lastName) +
                                    makeCell(user.userGroup) +
                                    makeCell(user.enabled)},
                        node);
                    }

                    function makeCell(text) {
                        text ? '' : text = 'не указано';
                        //console.log(clz);
                        return "<td>" + text + "</td>";
                    }


                    function getSelectedOptionValue(select) {
                        return select.options[select.selectedIndex].value;
                    }

                    return {
                        makeUsersTable: function(users) {
                            var tableBodyNode = query("#usersGrid tbody")[0];//returns NodeList, actually array with dojo extensions
                            tableBodyNode.innerHTML = '';
                            if (users && users.length) {
                                for (var i = 0; i < users.length; i++) {
                                    makeRow(users[i], tableBodyNode);
                                }
                            }
                        },
                        makeFilterTable: function(fire, event) {
                            event.preventDefault();
                            console.log("--makefiltertable");
                            console.log(event);
                            console.log(domForm.toObject("userListFilterForm"));
                            fire(domForm.toObject("userListFilterForm"));
                        },
                        toggleBtn: function(btn, enbl, text, event) {
                            console.log(arguments);
                            btn.disabled = enbl;
                            btn.innerHTML = text;
                            btn.value = text;
                        },
                        showError: function(error) {

                            fx.chain([
                                fx.wipeOut({node: 'usersGrid'}),
                                fx.wipeOut({node: 'userListFilterForm'}),
                                fx.wipeIn({node: 'errorAlert'}),
                                baseFx.fadeIn({node: 'errorAlert'})
                            ]).play();

                            var ed = query("#errorAlert pre")[0];
                            ed.innerHTML = "Message:" + error.message;
                            // alert(error);
                        }
                    };
                }
                var model = new Model();
                var vw = new View();

                notify("error", vw.showError);

                model.registerCallback('query', vw.makeUsersTable);

                model.query().then(function(srvUsers) {//bind ui after first call user list
                    var filterBtn = query("#userListFilterSubmit")[0];
                    var filterEnSelect = query("#userListFilterForm [name=enabled]")[0];
                    var filterGrpSelect = query("#userListFilterForm [name=userGroup]")[0];

                    model.registerCallback('beforeQuery',
                            lang.partial(vw.toggleBtn, filterBtn, true, 'Loading...'));
                    model.registerCallback('query',
                            lang.partial(vw.toggleBtn, filterBtn, true, 'Done'));
                    on(filterBtn, "click",
                            lang.partial(vw.makeFilterTable, model.query));
                    on(filterEnSelect, "change",
                            lang.partial(vw.toggleBtn, filterBtn, false, 'Apply Filters'));

                    on(filterGrpSelect, "change",
                            lang.partial(vw.toggleBtn, filterBtn, false, 'Apply Filters'));
                }); //first call
            });

        </script>
    </head>
    <body>
        <div class="navbar navbar-inverse navbar-fixed-top">
            <div class="navbar-inner">
                <div class="container-fluid">
                    <a class="brand" href="#">User list</a>
                </div>
            </div>
        </div>

        <div class="container-fluid">
            <div class="row-fluid">

                <!--=========left column=========================-->
                <div class="span2">
                    <form id="userListFilterForm">
                        <fieldset>
                            <legend>Filters</legend>
                            <span class="help-block">select, if need, the appropriate filters and apply them</span>
                            <label>Enabled user ?</label>
                            <select title=" Enabled User ?" 
                                    name="enabled">
                                <option value="" selected>Any</option>
                                <option value="y">Yes</option>
                                <option value="n">No</option>
                            </select>
                            <label>User group</label>
                            <select title=" User group ?" 
                                    name="userGroup">
                                <option value="" selected>Any</option>
                                <option value="speed-1000">speed-1000</option>
                                <option value="speed-512">speed-512</option>
                                <option value="speed-256">speed-256</option>
                                <option value="speed-128">speed-128</option>
                                <option value="speed-64">speed-64</option>
                                <option value="speed-32">speed-32</option>
                            </select>
                            <button id="userListFilterSubmit" 
                                    name="userListFilterSubmit"
                                    class="btn btn-primary"
                                    type="button"
                                    data-loading-text="Loading...">Apply Filters</button>
                        </fieldset>
                    </form>
                </div>
                <!--end left column-->
                <div class="span9">
                    <div id="errorAlert" class="alert alert-error">

                        <p>
                            <strong>К сожалению произошла ошибка,
                                пожалуйста скопируйте текст сообщения и вышлите разработчику
                            </strong>
                        </p>
                        <pre><!--ajax here--></pre>
                    </div>
                    <!--p>ADSL and DialUp users list below:</p-->
                    <table id="usersGrid" class="table table-hover">
                        <thead>
                            <tr>
                                <th>Id</th>
                                <th>Login</th>
                                <th>User</th>
                                <th>Group</th>
                                <th>Enabled?</th>
                            </tr>
                        </thead>
                        <tbody>
                            <!--ajax here-->
                        </tbody>
                    </table>
                </div>
            </div>
            <hr/>
            <footer>
                <span>2013 @IT Department</span>
                <a href="#">$HeadURL: http://iceline-acct.googlecode.com/svn/tags/1.0-beta-1/wi/src/main/webapp/index.html $</a>
            </footer>
        </div>


    </body>
</html>